package controller;

import dao.UserDAO;
import pojo.User;
import utils.DAOFactory;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by zyb on 14-12-11.
 */
@WebServlet(urlPatterns = {"*.action"})
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDAO userDAO = (UserDAO)DAOFactory.getInstance("UserDAO");
        request.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        String patternAction = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
        System.out.println("uri:"+uri);
//        System.out.println("patternAction:"+patternAction);

        if("/list".equals(patternAction)){
            try {
                List<User> userList = userDAO.findAll();
                request.setAttribute("userList",userList);
                request.getRequestDispatcher("/list.jsp").forward(request,response);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        else if("/add".equals(patternAction)){
            User user = new User();
            user.setAge(Integer.valueOf(request.getParameter("age")));
            user.setGender(request.getParameter("gender"));
            user.setPhone(request.getParameter("phone"));
            user.setUsername(request.getParameter("username"));
            try {
                userDAO.save(user);
                response.sendRedirect(request.getContextPath()+"/list.action");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        else if("/delete".equals(patternAction)){
            try {
                userDAO.delete(Integer.valueOf(request.getParameter("id")));
                response.sendRedirect(request.getContextPath()+"/list.action");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }
}
